<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;
use kartik\datetime\DateTimePicker;
use yii\helpers\Url;
/* @var $this yii\web\View */
/* @var $model common\models\Activity */
/* @var $form yii\widgets\ActiveForm */

?>
<div class="activity-form">

    <?php $form = ActiveForm::begin(['options'=>['enctype'=>'multipart/form-data','id'=>'main']]); ?>
    <?= Html::tag("div",'活动基本信息',['style'=>'font-weight:bold;'])?>
    <?= Html::beginTag("div",['style'=>'padding-left:50px;'])?>
    <?= $form->field($model, 'name')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'activity_catalog',['template'=>"{label}\n<div style='width:100%'>团购</div>\n{hint}\n\n{error}"])->label('活动类型')->textInput() ?>

    <?= $form->field($model, 'peoples',['template'=>"{label}\n<div style='width:100%'>满{input}人可开团</div>\n{hint}\n\n{error}"])->label('优惠方式')->textInput(['style'=>'width:50px;display:inline;margin:0 10px;']) ?>

    <?= $form->field($model, 'start_user_type',[
        'options'=>['class' => 'form-group form-md-radios'],
        'template' => '{label}<div class="md-radio-inline">{input}</div>{hint}{error}',
    ])->radioList(['全部','新用户','老用户'],
        [
            'item' => function($index, $label, $name, $checked, $value) {
                $checked=$checked?"checked":"";
                $return = '<div class="md-radio">';
                $return .= '<input type="radio" id="' . $name . $value . '" name="' . $name . '" value="' . $value . '" class="md-radiobtn"  '.$checked.'>';
                $return .= '<label for="' . $name . $value . '">
                    <span></span>
                    <span class="check"></span>
                    <span class="box"></span>' . ucwords($label) . '</label>';
                $return .= '</div>';
                return $return;
            }
        ]) ?>

    <?= $form->field($model, 'join_user_type',[
        'options'=>['class' => 'form-group form-md-radios'],
        'template' => '{label}<div class="md-radio-inline">{input}</div>{hint}{error}',
    ])->radioList(['全部','新用户','老用户'],
        [
            'item' => function($index, $label, $name, $checked, $value) {
                $checked=$checked?"checked":"";
                $return = '<div class="md-radio">';
                $return .= '<input type="radio" id="' . $name . $value . '" name="' . $name . '" value="' . $value . '" class="md-radiobtn"  '.$checked.'>';
                $return .= '<label for="' . $name . $value . '">
                    <span></span>
                    <span class="check"></span>
                    <span class="box"></span>' . ucwords($label) . '</label>';
                $return .= '</div>';
                return $return;
            }
        ]) ?>


    <?= $form->field($model, 'start_time')->widget(DateTimePicker::classname(), [
        'options' => ['placeholder' => '', 'autocomplete'=>'off'],
        'pluginOptions' => [
            'autoclose' => true,
            'todayHighlight' => true,
        ],
        'value'=>isset($model->start_time)?$model->start_time:'',
        'layout'=>'{input}{picker}'
    ]); ?>

    <?= $form->field($model, 'end_time')->widget(DateTimePicker::classname(), [
        'options' => ['placeholder' => '', 'autocomplete'=>'off'],
        'pluginOptions' => [
            'autoclose' => true,
            'todayHighlight' => true,
        ],
        'value'=>isset($model->end_time)?$model->end_time:'',
        'layout'=>'{input}{picker}'
    ]); ?>
    <?= Html::endTag("div")?>
    <?= Html::tag("div",'活动模板设置',['style'=>'font-weight:bold;'])?>
    <?= Html::beginTag("div",['style'=>'padding-left:50px;'])?>

    <?= $form->field($model, 'pic')->fileInput() ?>
    <?= Html::img($model->banner,['style'=>"height:50px;"])?>

    <?= $form->field($model, 'pic1')->fileInput() ?>
    <?= Html::img($model->other_entry,['style'=>"height:50px;"])?>

    <?= $form->field($model, 'other_entry_url')->textInput() ?>
    <?= $form->field($model, 'store_id')->textInput() ?>
    <?= $form->field($model, 'description')->textarea(['rows' => 6]) ?>
    <?= Html::endTag("div")?>

    <?= Html::tag("div",'活动分享设置',['style'=>'font-weight:bold;'])?>
    <?= Html::beginTag("div",['style'=>'padding-left:50px;'])?>
    <?= $form->field($model, 'share_title')->textInput() ?>
    <?= $form->field($model, 'pic2')->fileInput() ?>
    <?= Html::img($model->share_img,['style'=>"height:50px;"])?>

    <?= $form->field($model, 'share_remark')->textarea(['rows'=>3]) ?>
    <?= $form->field($model, 'share_url')->textInput() ?>
    <?= Html::endTag("div")?>

    <?= Html::tag("div",'活动商品管理',['style'=>'font-weight:bold;'])?>
    <?= Html::beginTag("div",['style'=>'padding-left:50px;'])?>

    <?php
        $arr=explode(",",$model->goods);
    foreach($arr as $key=>$goodid){?>

        <?=Html::beginTag("iframe",[
            'src'=>Url::to(['product/small-update','id'=>$goodid]),
            'style'=>['border-top'=>'none','border-left'=>'none','border-right'=>'none','border-bottom'=>'1px solid #f00','height'=>'800px','overflow-y'=>'auto'],
            'width'=>'100%',
            'id'=>'goodid'.($key+1)
        ])?>

        <?=Html::endTag('iframe')?>
    <?php }?>

    <?=Html::endTag('div')?>
    <?= Html::beginTag("div",['style'=>'padding-left:50px;'])?>
    <?=Html::button("继续添加商品",['onclick'=>'addProduct()','class' => 'btn btn-warning'])?>
    <?=Html::endTag('div')?>
    <?=Html::hiddenInput("totalgoods",count($arr),['id'=>'totalgoods'])?>
    <div class="form-group">
        <?=Html::hiddenInput("goods_info",'',['id'=>'goods_info'])?>
        <?= Html::button('保存', ['class' => 'btn btn-success','onclick'=>'tj()']) ?>
    </div>

    <?php ActiveForm::end(); ?>

</div>
<?php
$this->registerJs('$(".delProduct").click(function(){
        alert(1);
        $(this).prev("iframe").remove();
    });');
?>
<script>
    function addProduct(){
        // alert(1);
        var totalgoods=$("#totalgoods").val();
        while($('#goodid'+totalgoods).length==0){
            // console.log(totalgoods);
            totalgoods--;
            $("#totalgoods").val(totalgoods);

        }
        var html=' <iframe id="goodid'+(parseInt(totalgoods)+1)+'" src="/admin/product/small-create" width="100%" style="border-top: none; border-left: none; border-right: none; border-bottom: 1px solid #f00; height: 800px; overflow-y: auto;"></iframe>';


        //html=html.replace("id='goodid"+totalgoods+"'","id='goodid"+(totalgoods+1)+"'");
        // html.attr("id",'goodid'+(parseInt(totalgoods)+1));
         // console.log(html.attr("id"));
        $('#goodid'+totalgoods).after(html);

        $("#totalgoods").val(parseInt(totalgoods)+1);
        $('#goodid'+totalgoods).after('</div>');
        $('#goodid'+totalgoods).after('<?= Html::button("删除",['class'=>'btn btn-success delProduct','onclick'=>'delProduct(this)'])?>');
    }
    function delProduct(obj){
        //alert(obj.nextSibling);
        var totalgoods=$("#totalgoods").val();
        var iframe_id = obj.nextSibling.id;

        //删除id
        var idObject = document.getElementById(iframe_id);
        if (idObject != null)
            idObject.parentNode.removeChild(idObject);
        obj.remove();
        // console.log("goodid"+totalgoods==iframe_id,"goodsid"+totalgoods,iframe_id);
        if("goodid"+totalgoods==iframe_id){
            $("#totalgoods").val(parseInt(totalgoods)-1);
        }

    }

    function tj(){
        var flag=false;
        var totalgoods=$("#totalgoods").val();
        // alert(totalgoods);
        $("#goods_info").val("");
        for(var i=1;i<=parseInt(totalgoods);i++){
            // $(document.getElementById('goodid'+i).contentWindow.document.body).find("form").attr("action","/admin/product/validate");
            if($("#goodid"+i).length>0){

                form=$(document.getElementById('goodid'+i).contentWindow.document.body).find("form");//.submit();

                var goods_info=$("#goods_info").val();
                $("#goods_info").val(goods_info+"@@@"+form.serialize());
                //表单提交
                $.ajax({
                    url  : '/admin/product/validate',
                    type  : "post",
                    data  : form.serialize(),
                    dataType: "json",
                    cache:false,  //默认是true，但是一般不做缓存
                    processData:false, //用于对data参数进行序列化处理，这里必须false；如果是true，就会将FormData转换为String类型
                    contentType:false,  //一些文件上传http协议的关系，自行百度，如果上传的有文件，那么只能设置为false
                    success: function (response){
                        var count = Object.keys(response).length;
                        // console.log(count);
                        if(count>0){
                            for(let item in response) {
                                // console.log(item,response[item][0]);
                                form.find("#"+item).parent().addClass("has-error");
                                form.find("#"+item).parent().find(".help-block").html(response[item][0]);
                            }
                        }else{
                            // form.submit();
                            form.find(".has-error").removeClass("has-error");
                            form.find(".help-block").html("");


                            $("#main").submit();
                        }

                    },
                    error : function (){
                        alert('系统错误');
                        return false;
                    }
                });
            }



             // console.log($result);
        }
        return flag;
    }




</script>
